package com.craftplay.interceptor;

import com.craftplay.model.HostHolder;
import com.craftplay.model.User;
import com.craftplay.util.UserAgentUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LoginRequiredInterceptor.class);


    @Autowired
    HostHolder hostHolder;

    @Autowired
    private Environment env;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if (env.getProperty("isDebug").equals("true")) {
            return true;
        }
        if (!UserAgentUtil.isWechat(httpServletRequest)) {
            return true;
        }
        if (hostHolder.getUser() == null) {
            String currUrl = httpServletRequest.getRequestURI();
            if (currUrl.contains("/play")) {
                currUrl = currUrl.substring(5);
            }

            //微信支付回调不校验
            if (currUrl.contains("/callBack/notify/order")) {
                logger.info("微信支付回调");
                return true;
            }

            httpServletResponse.sendRedirect("/play/weixin/authorize?returnUrl=" + currUrl);
            logger.info("请求接口:" + httpServletRequest.getRequestURI() + ", 方式:" +
                    httpServletRequest.getMethod());
            return false;
        }
        User user = hostHolder.getUser();
        logger.info("请求接口:" + httpServletRequest.getRequestURI() + ", 方式:" +
                httpServletRequest.getMethod() + ", 用户ID:" + user.getUserId() + ", 用户名:" + user.getNickname());

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }

}